/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bifang.gwt.client.service.content;

import han.bifang.gwt.client.common.Content;
import han.bifang.gwt.client.common.ContentChangeListener;
import han.bifang.gwt.client.common.EntityConstants;
import han.bifang.gwt.client.common.GwtContext;
import han.bifang.gwt.client.common.RequestObject;
import han.bifang.gwt.client.common.ResponseObject;
import han.bifang.gwt.client.common.entity.MappingService;
import han.bifang.gwt.client.common.entity.Service;
import han.bifang.gwt.client.common.util.StringUtils;
import han.bifang.gwt.client.communicate.BifangGWTServiceAsync;
import han.bifang.gwt.client.service.ServiceContentConstants;
import han.bifang.gwt.client.service.ServiceMessages;

import java.util.ArrayList;
import java.util.HashMap;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
import com.google.gwt.user.client.ui.HTMLTable.ColumnFormatter;

/**
 * 
 * @Author Kent
 */
public class ResultPanel extends Content implements SqlListener {
	private ServiceMessages cons;
	private GwtContext context;
	private String serhql;
	private String maphql;
	private BifangGWTServiceAsync service;
	private DecoratorPanel panel = null;
	private int size = 10;
	private int currentPage = 1;
	private ArrayList p;

	private AsyncCallback<ResponseObject> cb = new AsyncCallback<ResponseObject>() {
		public void onSuccess(ResponseObject res) {
			String code = res.getCode();
			if (!code.equals("0")) {
				Window.alert("There was an error: " + res.getMsg());
				return;
			}
			ArrayList ret = (ArrayList) res.getResponse();
			int total = (Integer) ret.get(0);
			// Window.alert("total " + total);
			ArrayList list = (ArrayList) ret.get(1);
			if (total != 0) {
				VerticalPanel v = new VerticalPanel();
				v.setWidth("100%");
				v.setSpacing(5);

				Grid table = new Grid(list.size() + 1, 7);
				table.setCellPadding(1);
				table.setCellSpacing(1);
				table.setBorderWidth(1);

				ColumnFormatter cf = table.getColumnFormatter();

				cf.setWidth(0, "10%");
				cf.setWidth(1, "10%");
				cf.setWidth(2, "10%");
				cf.setWidth(3, "12%");
				cf.setWidth(4, "10%");
				cf.setWidth(5, "30%");
				cf.setWidth(6, "6%");

				CellFormatter ff = table.getCellFormatter();
				ff.setStyleName(0, 0, "tablecol");
				ff.setStyleName(0, 1, "tablecol");
				ff.setStyleName(0, 2, "tablecol");
				ff.setStyleName(0, 3, "tablecol");
				ff.setStyleName(0, 4, "tablecol");
				ff.setStyleName(0, 5, "tablecol");
				ff.setStyleName(0, 6, "tablecol");

				table.setHTML(0, 0, cons.name());
				table.setHTML(0, 1, cons.code());
				table.setHTML(0, 2, cons.defaultVersion());
				table.setHTML(0, 3, cons.createTime());
				table.setHTML(0, 4, cons.status());
				table.setHTML(0, 5, cons.desc());
				table.setHTML(0, 6, "&nbsp;");

				for (int i = 1, j = list.size() + 1; i < j; i++) {
					Service s = (Service) list.get(i - 1);
					table.setHTML(i, 0, s.getServiceName());
					table.setHTML(i, 1, s.getServiceCode());
					table.setHTML(i, 2, StringUtils.isEmpty(s
							.getDefaultVersion()) ? "&nbsp;" : s
							.getDefaultVersion());
					table.setHTML(i, 3, s.getCreateTime());
					table.setHTML(i, 4, s.getStatus().equals(
							EntityConstants.SERVICE_STATUS_PUBLISHED) ? cons
							.published() : cons.unpublished());
					table.setHTML(i, 5, s.getDescription());

					Button b = new Button(cons.view());
					ViewClickListener l = new ViewClickListener();
					l.setContentChangeListener(listener);
					l.setId(s.getId());
					b.addClickListener(l);

					table.setWidget(i, 6, b);

				}
				v.add(table);
				v.add(new HTML("&nbsp;"));
				HorizontalPanel h = new HorizontalPanel();
				h.setWidth("100%");
				h.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
				h.add(new HTML(cons.page(total, currentPage)));
				v.add(h);
				if (total > 1) {

					if (currentPage > 1) {
						Button pre = new Button(cons.previous());
						pre.addClickListener(new ClickListener() {
							public void onClick(Widget sender) {
								currentPage--;
								searchService(serhql, currentPage, size);
							}

						});
						// h.add(new HTML("&nbsp;&nbsp;"));
						h.add(pre);
					}
					if (currentPage < total) {
						Button n = new Button(cons.next());
						n.addClickListener(new ClickListener() {
							public void onClick(Widget sender) {
								currentPage++;
								searchService(serhql, currentPage, size);
							}

						});
						// h.add(new HTML("&nbsp;&nbsp;"));
						h.add(n);

					}

				}
				panel.setWidget(v);
			}else{
				panel.setWidget(new HTML(cons.noResult()));
			}

		}

		public void onFailure(Throwable caught) {
			Window.alert("There was an error: " + caught.toString());
		}
	};

	private AsyncCallback<ResponseObject> cb1 = new AsyncCallback<ResponseObject>() {
		public void onSuccess(ResponseObject res) {
			String code = res.getCode();
			if (!code.equals("0")) {
				Window.alert("There was an error: " + res.getMsg());
				return;
			}
			ArrayList ret = (ArrayList) res.getResponse();
			int total = (Integer) ret.get(0);
			// Window.alert("total " + total);
			ArrayList list = (ArrayList) ret.get(1);
			if (total != 0) {
				VerticalPanel v = new VerticalPanel();
				v.setWidth("100%");
				v.setSpacing(5);

				Grid table = new Grid(list.size() + 1, 5);
				table.setCellPadding(1);
				table.setCellSpacing(1);
				table.setBorderWidth(1);

				ColumnFormatter cf = table.getColumnFormatter();

				cf.setWidth(0, "15%");
				cf.setWidth(1, "15%");
				cf.setWidth(2, "15%");
				cf.setWidth(3, "35%");
				cf.setWidth(4, "10%");

				CellFormatter ff = table.getCellFormatter();
				ff.setStyleName(0, 0, "tablecol");
				ff.setStyleName(0, 1, "tablecol");
				ff.setStyleName(0, 2, "tablecol");
				ff.setStyleName(0, 3, "tablecol");
				ff.setStyleName(0, 4, "tablecol");

				table.setHTML(0, 0, cons.name());
				table.setHTML(0, 1, cons.localCode());
				table.setHTML(0, 2, cons.remoteCode());
				table.setHTML(0, 3, cons.desc());
				table.setHTML(0, 4, "&nbsp;");

				for (int i = 1, j = list.size() + 1; i < j; i++) {
					MappingService s = (MappingService) list.get(i - 1);
					table.setHTML(i, 0, s.getName());
					table.setHTML(i, 1, s.getLocalCode());
					table.setHTML(i, 2, s.getRemoteCode());
					table.setHTML(i, 3, s.getDescription());

					Button b = new Button(cons.view());
					ViewClickListener1 l = new ViewClickListener1();
					l.setContentChangeListener(listener);
					l.setId(s.getId());
					l.setDomainId(s.getDomainId());
					b.addClickListener(l);

					table.setWidget(i, 4, b);

				}
				v.add(table);
				v.add(new HTML("&nbsp;"));
				HorizontalPanel h = new HorizontalPanel();
				h.setWidth("100%");
				h.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
				h.add(new HTML(cons.page(total, currentPage)));
				v.add(h);
				if (total > 1) {

					if (currentPage > 1) {
						Button pre = new Button(cons.previous());
						pre.addClickListener(new ClickListener() {
							public void onClick(Widget sender) {
								currentPage--;
								searchMappingService(serhql, currentPage, size);
							}

						});
						// h.add(new HTML("&nbsp;&nbsp;"));
						h.add(pre);
					}
					if (currentPage < total) {
						Button n = new Button(cons.next());
						n.addClickListener(new ClickListener() {
							public void onClick(Widget sender) {
								currentPage++;
								searchMappingService(serhql, currentPage, size);
							}

						});
						// h.add(new HTML("&nbsp;&nbsp;"));
						h.add(n);

					}

				}
				panel.setWidget(v);
			}else{
				panel.setWidget(new HTML(cons.noResult()));
			}

		}

		public void onFailure(Throwable caught) {
			Window.alert("There was an error: " + caught.toString());
		}
	};

	public ResultPanel(ServiceMessages scons, BifangGWTServiceAsync s,
			GwtContext context, String servicehql, String mapservicehql) {

		this.cons = scons;
		this.context = context;
		this.service = s;

		this.serhql = servicehql;
		this.maphql = mapservicehql;

		panel = new DecoratorPanel();
		panel.setWidth("100%");
		HTML noResult = new HTML(cons.noResult());
		panel.setWidget(noResult);

		initWidget(panel);

	}

	public void onMappingServiceSql(String sql) {
		this.maphql = sql;
		currentPage = 1;
		searchMappingService(maphql, 0, size);

	}

	public void onServiceSql(String sql) {
		this.serhql = sql;
		currentPage = 1;
		searchService(serhql, 0, size);

	}

	private void searchService(String hql, int page, int size) {
		RequestObject req = new RequestObject();
		req
				.setAction("han.bifang.gwt.server.action.service.SearchServiceAction");
		p = new ArrayList();
		p.add(hql);
		p.add(page);
		p.add(size);
		req.setRequest(p);
		service.call(req, cb);
	}

	private void searchMappingService(String hql, int page, int size) {
		RequestObject req = new RequestObject();
		req
				.setAction("han.bifang.gwt.server.action.service.SearchMappingServiceAction");
		p = new ArrayList();
		p.add(hql);
		p.add(page);
		p.add(size);
		req.setRequest(p);
		service.call(req, cb1);
	}

	public void refreshService() {
		RequestObject req = new RequestObject();
		req
				.setAction("han.bifang.gwt.server.action.service.SearchServiceAction");
		if(p == null){
			p = new ArrayList();
			p.add(null);
			p.add(currentPage);
			p.add(size);
		}
		
		req.setRequest(p);
		service.call(req, cb);
	}
	
	public void refreshMappingService() {
		RequestObject req = new RequestObject();
		req
				.setAction("han.bifang.gwt.server.action.service.SearchMappingServiceAction");
		if(p == null){
			p = new ArrayList();
			p.add(null);
			p.add(currentPage);
			p.add(size);
		}
		req.setRequest(p);
		service.call(req, cb1);
	}

	private static class ViewClickListener implements ClickListener {
		private ContentChangeListener listener;
		private String id;

		public void setContentChangeListener(ContentChangeListener l) {
			listener = l;
		}

		public void setId(String id) {
			this.id = id;
		}

		public void onClick(Widget sender) {
			HashMap p = new HashMap();
			p.put("id", id);
			
			listener.onContentChanged(ServiceContentConstants.SEARCH_RESULT,
					ServiceContentConstants.SERVICE_ROOT, p);

		}

	}

	private static class ViewClickListener1 implements ClickListener {
		private ContentChangeListener listener;
		private String id;
		private String domainId;

		public void setDomainId(String domainId) {
			this.domainId = domainId;
		}

		public void setContentChangeListener(ContentChangeListener l) {
			listener = l;
		}

		public void setId(String id) {
			this.id = id;
		}

		public void onClick(Widget sender) {
			HashMap p = new HashMap();
			p.put("id", id);
			p.put("domainId", domainId);
			listener.onContentChanged(ServiceContentConstants.SEARCH_RESULT,
					ServiceContentConstants.REMOTE_SERVICE_ROOT, p);

		}

	}

}
